import axios from "axios"
import { Toast } from 'vant';
import 'vant/lib/index.css';
import router from "@router/index.js";

class Axios {
    constructor(options) {
        this.axiosInstance = axios.create(options)
        this.interceptors()
    }
    interceptors() {//拦截器
        // 添加请求拦截器
        this.axiosInstance.interceptors.request.use(function (config) {
            // 在发送请求之前做些什么
            let token = localStorage.getItem("jwtToken")
            if (token) {
                config.headers.token = token
            }
            return config;
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        });

        // 添加响应拦截器
        this.axiosInstance.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            switch (response.data.code) {
                case 1000://成功
                    {
                        Toast.success(response.data.msg)
                        break;
                    }
                case 1001://用户不存在
                    {
                        Toast.fail(response.data.msg)
                        break;
                    }
                case 1002:
                    {
                        Toast.fail(response.data.msg)
                        break;
                    }
                case 1003://没登录
                    {
                        Toast.fail(response.data.msg)
                        router.replace("/login")
                        break;
                    }
                case 1004://账号被挤下线
                    {
                        Toast.fail(response.data.msg)
                        router.replace("/login")
                        break;
                    }
                case 1005://超时
                    {
                        Toast.fail(response.data.msg)
                        router.replace("/login")
                        break;
                    }
                case 1006://刷新token
                    {
                        let token = response.data.data//获取新的token
                        localStorage.setItem("jwtToken", token)//替换旧的token

                        let config = response.config
                        config.headers.token = token//设置最新的请求头的token

                        return this.axiosInstance.request(config)//重新发送当前的请求
                    }
                default:
                    break;
            }
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }


}

export default Axios
